package com.example.ai.service;

import com.example.ai.dto.community.CommunityShareRequest;
import com.example.ai.dto.community.CommunityShareResponse;
import com.example.ai.entity.ShareLike;
import com.example.ai.model.CommunityShare;
import com.example.ai.model.User;
import com.example.ai.model.WrongQuestion;
import com.example.ai.repository.CommunityShareRepository;
import com.example.ai.repository.UserRepository;
import com.example.ai.repository.WrongQuestionRepository;
import com.example.ai.repository.ShareLikeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class CommunityService {

    private final CommunityShareRepository communityShareRepository;
    private final WrongQuestionRepository wrongQuestionRepository;
    private final UserRepository userRepository;
    private final ShareLikeRepository shareLikeRepository;
    private final UserService userService;

    @Transactional
    public CommunityShareResponse shareWrongQuestion(CommunityShareRequest request) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found"));

        // 检查错题是否存在且属于当前用户
        WrongQuestion wrongQuestion = wrongQuestionRepository.findById(request.getWrongQuestionId())
                .orElseThrow(() -> new RuntimeException("Wrong question not found"));

        if (!wrongQuestion.getUser().getId().equals(user.getId())) {
            throw new RuntimeException("Not authorized to share this wrong question");
        }

        // 检查是否已经分享过
        if (communityShareRepository.existsByWrongQuestionId(wrongQuestion.getId())) {
            throw new RuntimeException("This wrong question has already been shared");
        }

        CommunityShare share = new CommunityShare();
        share.setUser(user);
        share.setWrongQuestion(wrongQuestion);
        share.setShareNote(request.getShareNote());
        share = communityShareRepository.save(share);

        return convertToResponse(share);
    }

    @Transactional(readOnly = false)
    public Page<CommunityShareResponse> getCommunityShares(Pageable pageable) {
        return communityShareRepository.findAllByOrderByCreatedAtDesc(pageable)
                .map(this::convertToResponse);
    }

    @Transactional
    public void incrementViewCount(Long shareId) {
        CommunityShare share = communityShareRepository.findById(shareId)
                .orElseThrow(() -> new RuntimeException("Share not found"));
        share.setViewCount(share.getViewCount() + 1);
        communityShareRepository.save(share);
    }

    @Transactional
    public boolean toggleLike(Long shareId,Long userId) {
        CommunityShare share = communityShareRepository.findById(shareId)
                .orElseThrow(() -> new RuntimeException("Share not found"));
        // 检查是否已经点赞
        Optional<ShareLike> existingLike = shareLikeRepository
            .findByShareIdAndUserId(shareId, userId);
        
        if (existingLike.isPresent()) {
            // 如果已经点赞，则取消点赞
            shareLikeRepository.delete(existingLike.get());
            //帖子点赞-1
            share.setLikeCount(share.getLikeCount() - 1);
            communityShareRepository.save(share);
            return false;
        } else {
            // 如果未点赞，则添加点赞
            ShareLike newLike = new ShareLike();
            newLike.setShareId(shareId);
            newLike.setUserId(userId);
            newLike.setCreatedAt(LocalDateTime.now());
            shareLikeRepository.save(newLike);
            //帖子增加点赞
            share.setLikeCount(share.getLikeCount() + 1);
            communityShareRepository.save(share);
            return true;
        }
    }

    @Transactional(readOnly = true)
    public Page<CommunityShareResponse> getLikedShares(Long userId, Pageable pageable) {
        // 先获取用户点赞的分享ID列表
        Page<ShareLike> likes = shareLikeRepository.findByUserId(userId, pageable);
        
        // 将ShareLike转换为CommunityShareResponse
        return likes.map(like -> {
            CommunityShare share = communityShareRepository.findById(like.getShareId())
                .orElseThrow(() -> new RuntimeException("Share not found"));
            return convertToResponse(share);
        });
    }

    private CommunityShareResponse convertToResponse(CommunityShare share) {
        CommunityShareResponse response = new CommunityShareResponse();
        response.setId(share.getId());
        response.setUsername(share.getUser().getUsername());
        response.setUseravatar(share.getUser().getAvatar());
        response.setWrongQuestionId(share.getWrongQuestion().getId());
        response.setUserAnswer(share.getWrongQuestion().getUserAnswer());
        response.setCorrectAnswer(share.getWrongQuestion().getCorrectAnswer());
        response.setShareNote(share.getShareNote());
        response.setViewCount(share.getViewCount());
        response.setLikeCount(share.getLikeCount());
        response.setCreatedAt(share.getCreatedAt());
        response.setUpdatedAt(share.getUpdatedAt());
        
        // 添加日志
        System.out.println("Converting share to response: " + share.getId());
        System.out.println("WrongQuestion ID: " + share.getWrongQuestion().getId());
        
        return response;
    }
} 